package ldh.im.fxbase.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CloseFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(CloseFactory.class);

    private static final CloseFactory instance = new CloseFactory();
    private Map<String, Closeable> closeableMap = new ConcurrentHashMap<>();

    private CloseFactory(){}

    public static final CloseFactory getInstance() {
        return instance;
    }

    public void addCloseable(String key, Closeable closeable) {
        closeableMap.putIfAbsent(key, closeable);
    }

    public Closeable getCloseable(String key) {
       return closeableMap.get(key);
    }

    public void closeByKeyPrefix(String keyPrefix) {
        List<String> needCloseable = new ArrayList<>();
        for (String key : closeableMap.keySet()) {
            if (key.startsWith(keyPrefix)) {
                needCloseable.add(key);
            }
        }
        for (String key : needCloseable) {
            Closeable closeable = closeableMap.get(key);
            close(closeable);
        }
    }

    public Closeable remove(String key) {
        return closeableMap.remove(key);
    }

    public void closeAll() {
        for (Map.Entry<String, Closeable> entry : closeableMap.entrySet()) {
            Closeable closeable = entry.getValue();
            close(closeable);
        }
        LOGGER.info("closeAll!!!");
    }

    private void close(Closeable closeable) {
        try {
            closeable.close();
        } catch (Exception e) {
            LOGGER.error("close error, error: {}", e);
        }
    }
}
